import { Image, Text, View, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import SearchNew from '@/components/SearchNew';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import { regeo } from '@/dataTransfer/address';
import pLoc from '@/images/common/location2.png';
import './index.scss';

const SelfTakePonit = ({ dispatch, selfTakeList = [], selfTakeFinished = false }) => {
  const [keyWords, setKeyWords] = useState('');
  const [curLocation, setCurLocation] = useState(null);
  const [cityStr, setCityStr] = useState('');

  const router = useRouter();
  const { params = {} } = router;

  const getLoc = debounce((showToast = false) => {
    showToast &&
      Taro.showToast({
        title: '定位中，请稍后',
        duration: 2000,
        icon: 'none',
      });
    Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      timeout: 5000,
      success: (res) => {
        const { latitude, longitude } = res;
        const timeStamp = new Date().getTime();
        setCurLocation({ latitude, longitude });
        utils.setLocalStorage('location', { latitude, longitude, timeStamp });
      },
      fail: () => {
        //   setNoAuth(true);
      },
    });
  }, 5000);

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      getLoc();
    }
  };

  const getLocationCity = () => {
    regeo(curLocation)
      .then(({ city, province, district }) => {
        setCityStr((city ?? province) + ' ' + district);
      })
      .catch(console.warn);
  };

  const showMap = (shopBaseInfo) => {
    Taro.openLocation({
      latitude: parseFloat(shopBaseInfo.latitude),
      longitude: parseFloat(shopBaseInfo.longtitude),
      scale: 15,
      name: shopBaseInfo.name || '',
      address: shopBaseInfo.address || '',
    });
  };

  const handleSearch = (keywords) => {
    setKeyWords(keywords);
  };

  const getData = () => {
    dispatch({
      type: 'otherApi/getSelfTakeListModel',
      payload: {
        storeId: parseInt(params.storeId),
        pageSize: 10,
        lon: curLocation.longitude,
        lat: curLocation.latitude,
        name: keyWords,
      },
    });
  };

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !selfTakeFinished && selfTakeList?.length > 0 && getData();
  }, 1200);

  useEffect(() => {
    getLocation();
  }, []);

  useEffect(() => {
    curLocation && getLocationCity();
  }, [curLocation]);

  useEffect(() => {
    curLocation && getData();
  }, [keyWords, curLocation]);

  return (
    <View className="selfTakeShop">
      <View className="searchLine">
        <SearchNew defaultValue={keyWords} handleSearch={handleSearch} />
      </View>
      <View className="locationLabelLine txt24 gray flex-row--center">当前定位</View>
      <View className="locationDetailLine flex-row-spaceBetween-center">
        <View className="txt24">{cityStr}</View>
        <View className="txt24 customePageStyle" onClick={() => getLoc(true)}>
          重新定位
        </View>
      </View>
      <ScrollView
        className="shopList"
        scrollY
        lowerThreshold={200}
        onScrollToLower={handleScrollToLower}
      >
        {selfTakeList.length > 0 ? (
          selfTakeList.map((shop) => {
            let timeStrList = [];
            switch (shop.businessHourType) {
              case 1:
                timeStrList[0] = '全天';
                break;
              case 2:
                let times = '';
                shop.orgBusinessHourList.length > 0 &&
                  shop.orgBusinessHourList.map((item) => {
                    times += item.dayList.join('、');
                  });
                timeStrList[0] = '（周一至周日）' + times;
                break;
              case 3:
                timeStrList =
                  shop.orgBusinessHourList.length > 0 &&
                  shop.orgBusinessHourList.map((item) => {
                    let timew = item.dayList.join('、');
                    let day = item.weekdayList.join('、');
                    return '（' + day + '）' + timew;
                  });
                break;
              default:
                break;
            }

            return (
              <View className="shop mb16">
                <View className="line flex-row-spaceBetween-center" onClick={() => showMap(shop)}>
                  <Text className="name txt28 txtDot">{shop.name}</Text>
                  <Text className="txt24 bold">{shop.distance > 50 ? '>50' : shop.distance}km</Text>
                </View>
                <View className="line mt16 flex-row--center" onClick={() => showMap(shop)}>
                  <Image className="locImg" src={pLoc} />
                  <Text className="txt24 gray txtDot addr">{shop.address}</Text>
                </View>
                <View className="diliver"></View>
                <View className="line work txt24 gray flex-row">
                  <View className="workLabel">营业时间：</View>
                  <View className="workTime flex-column">
                    {timeStrList.length > 0 &&
                      timeStrList.map((timeStr) => {
                        return <View className="time">{timeStr}</View>;
                      })}
                  </View>
                </View>
              </View>
            );
          })
        ) : (
          <View className="noShop"></View>
        )}
        {selfTakeList.length > 0 && selfTakeFinished && (
          <View className="noMore txt24 gray flex-row-center-center">没有更多了~</View>
        )}
      </ScrollView>
    </View>
  );
};

export default connect(({ otherApi }) => ({
  selfTakeList: otherApi.selfTakeList,
  selfTakeFinished: otherApi.selfTakeFinished,
}))(SelfTakePonit);
